﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace MISTBowl_Brackets
{
	public static class TickBasedRandom
	{
		static long ticks;
		static Random rng = new Random(0);

		public static int GetInteger(int min, int max)
		{
			try
			{
				long currentTicks = DateTime.UtcNow.Ticks;
				if (currentTicks != ticks)
				{
					rng = new Random((int)(ticks = currentTicks));
				}
				return rng.Next(min, max + 1);
			}
			catch (Exception e)
			{
				Traceback.Write("At int GetInteger(int, int");
				throw e;
			}
		}

		public static T[] SortRandom<T>(this IEnumerable<T> input)
		{
			try
			{
				var inputList = input.ToList();
				var output = new List<T>();
				while (inputList.ToArray().Length > 0)
				{
					var index = GetInteger(0, inputList.ToArray().Length - 1);
					output.Add(inputList.ElementAt(index));
					inputList.RemoveAt(index);
				}
				return output.ToArray();
			}
			catch (Exception e)
			{
				Traceback.Write("At T[] SortRandom<T>(IEnumerable<T>) (class TickBasedRandom):");
				throw e;
			}
		}
	}
}